﻿using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DotNetStar.TheKing.Web.Pages.Account
{
    using DotNetStar.TheKing.Infrastructure;
    using Microsoft.AspNetCore.Mvc;
    using Services;
    using System.ComponentModel.DataAnnotations;

    public class FindPwdModel:PageModel
    {
        private readonly UserService _userService;
        private readonly VerifyCodeService _verifyCodeService;


        public FindPwdModel(UserService userService,
            VerifyCodeService verifyCodeService)
        {
            _userService = userService;
            this._verifyCodeService = verifyCodeService;
        }
        
        public IActionResult OnGet()
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToPage("/Error", new { message = "请先登出当前帐号" });
            }
            return Page();
        }

        public async Task<IActionResult> OnPostAsync(string account, string code, string password)
        {
            if (account.IsNullOrWhiteSpace())
            {
                return StatusCode(400, "帐号不能为空");
            }

            if (code.IsNullOrWhiteSpace())
            {
                return StatusCode(400, "验证码不能为空");
            }

            var user = await _userService.GetUserAsync(account,out var accountType);
            if (user == null)
            {
                return StatusCode(400, "输入的帐号不存在");
            }

            var validateResult = _verifyCodeService.VerifyCode(account, code);
            if (!validateResult)
            {
                return StatusCode(400, "验证码不正确");
            }

            if (password.Length < 8 || password.Length > 25)
            {
                return StatusCode(400, "密码只能设置8-25个字符");
            }

            try
            {
                await _userService.ResetPasswordAsync(user, password);

                return StatusCode(200);
            }
            catch (Exception ex)
            {
                return StatusCode(400, ex.Message);
            }
        }

    }
}
